#!/usr/bin/env python3
"""
Ford URL0 简化逆向分析脚本
使用现有的WebDriver基础设施分析 URL0
"""

import json
import time
import sys
import os

# 添加src目录到路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from src.base import BaseWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class SimpleURL0Analyzer:
    """简化的URL0分析器"""
    
    def __init__(self):
        self.base_driver = None
        self.driver = None
        self.wait = None
        self.url0 = None
        self.results = {
            "analysis_date": time.strftime("%Y-%m-%d %H:%M:%S"),
            "target_url": "",
            "page_info": {},
            "models_found": [],
            "specification_links": [],
            "api_calls_detected": []
        }
    
    def load_config(self):
        """加载配置文件"""
        try:
            with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
                config = json.load(f)
            
            self.url0 = config.get('sub_model', {}).get('url0')
            if not self.url0:
                print("❌ 未找到url0配置")
                return False
            
            self.results["target_url"] = self.url0
            print(f"✅ 目标URL: {self.url0}")
            return True
            
        except Exception as e:
            print(f"❌ 加载配置失败: {e}")
            return False
    
    def setup_driver(self):
        """使用现有的WebDriver基础设施"""
        try:
            print("🔧 初始化WebDriver...")
            self.base_driver = BaseWebDriver()
            self.base_driver.setup_driver()
            self.driver = self.base_driver.driver
            self.wait = WebDriverWait(self.driver, 15)
            print("✅ WebDriver初始化成功")
            return True
        except Exception as e:
            print(f"❌ WebDriver初始化失败: {e}")
            return False
    
    def navigate_and_analyze(self):
        """导航到URL0并进行基础分析"""
        try:
            print(f"🌐 导航到: {self.url0}")
            self.driver.get(self.url0)
            
            # 等待页面加载
            time.sleep(5)
            
            # 获取基础页面信息
            page_title = self.driver.title
            final_url = self.driver.current_url
            
            self.results["page_info"] = {
                "title": page_title,
                "final_url": final_url,
                "redirected": final_url != self.url0
            }
            
            print(f"📄 页面标题: {page_title}")
            print(f"📍 最终URL: {final_url}")
            
            if final_url != self.url0:
                print("⚠️  检测到URL重定向")
            
            return True
            
        except Exception as e:
            print(f"❌ 页面导航失败: {e}")
            return False
    
    def find_vehicle_models(self):
        """查找页面上的车款信息"""
        try:
            print("🔍 查找车款信息...")
            
            # 简单的车款查找策略
            model_selectors = [
                'h1, h2, h3, h4',  # 标题元素
                'a[href*="focus"]',  # 包含focus的链接
                'div[class*="model"], div[class*="vehicle"], div[class*="car"]',  # 车款相关的div
                'button, a',  # 所有按钮和链接
            ]
            
            models_found = []
            
            for selector in model_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"  📋 选择器 '{selector}' 找到 {len(elements)} 个元素")
                    
                    for elem in elements[:5]:  # 只检查前5个
                        try:
                            text = elem.text.strip()
                            href = elem.get_attribute('href')
                            
                            if text and len(text) > 2 and len(text) < 200:  # 合理的文本长度
                                model_info = {
                                    "text": text,
                                    "tag": elem.tag_name,
                                    "href": href,
                                    "selector": selector
                                }
                                models_found.append(model_info)
                                
                        except Exception as e:
                            continue
                            
                except Exception as e:
                    print(f"    ❌ 选择器失败: {e}")
                    continue
            
            # 去重
            unique_models = []
            seen_texts = set()
            
            for model in models_found:
                text_lower = model['text'].lower()
                if text_lower not in seen_texts:
                    seen_texts.add(text_lower)
                    unique_models.append(model)
            
            self.results["models_found"] = unique_models[:15]
            print(f"✅ 发现 {len(unique_models)} 个潜在车款信息")
            
            return unique_models
            
        except Exception as e:
            print(f"❌ 车款查找失败: {e}")
            return []
    
    def find_specification_elements(self):
        """查找规格相关的元素"""
        try:
            print("🔍 查找规格相关元素...")
            
            # 规格相关的关键词
            spec_keywords = [
                'specification', 'spec', 'full spec',
                'see full specification', 'view specification',
                'details', 'more details', 'full details',
                'configure', 'build your', 'explore'
            ]
            
            spec_elements = []
            
            for keyword in spec_keywords:
                try:
                    # 使用XPath查找包含关键词的文本
                    xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{keyword}')]"
                    elements = self.driver.find_elements(By.XPATH, xpath)
                    
                    print(f"  🔍 关键词 '{keyword}' 找到 {len(elements)} 个元素")
                    
                    for elem in elements[:3]:  # 只检查前3个
                        try:
                            text = elem.text.strip()
                            href = elem.get_attribute('href')
                            onclick = elem.get_attribute('onclick')
                            
                            if text and len(text) > 2:
                                spec_info = {
                                    "text": text,
                                    "keyword": keyword,
                                    "tag": elem.tag_name,
                                    "href": href,
                                    "onclick": onclick,
                                    "class": elem.get_attribute('class')
                                }
                                spec_elements.append(spec_info)
                                
                        except Exception as e:
                            continue
                            
                except Exception as e:
                    print(f"    ❌ 关键词 '{keyword}' 搜索失败: {e}")
                    continue
            
            # 去重
            unique_specs = []
            seen_texts = set()
            
            for spec in spec_elements:
                text_lower = spec['text'].lower()
                if text_lower not in seen_texts:
                    seen_texts.add(text_lower)
                    unique_specs.append(spec)
            
            self.results["specification_links"] = unique_specs[:10]
            print(f"✅ 发现 {len(unique_specs)} 个规格相关元素")
            
            return unique_specs
            
        except Exception as e:
            print(f"❌ 规格元素查找失败: {e}")
            return []
    
    def detect_dynamic_content(self):
        """检测动态内容和可能的API调用"""
        try:
            print("🔍 检测页面动态内容...")
            
            # 检查页面是否包含常见的JavaScript框架
            page_source = self.driver.page_source.lower()
            
            frameworks_detected = {
                "react": "react" in page_source,
                "angular": "angular" in page_source,
                "vue": "vue" in page_source,
                "jquery": "jquery" in page_source
            }
            
            # 统计页面元素
            element_counts = {
                "total_links": len(self.driver.find_elements(By.TAG_NAME, 'a')),
                "total_buttons": len(self.driver.find_elements(By.TAG_NAME, 'button')),
                "total_scripts": len(self.driver.find_elements(By.TAG_NAME, 'script')),
                "total_images": len(self.driver.find_elements(By.TAG_NAME, 'img'))
            }
            
            # 查找可能的API调用线索
            api_indicators = []
            
            # 查找包含'api'的URL或文本
            api_elements = self.driver.find_elements(By.XPATH, "//*[contains(@href, 'api') or contains(@src, 'api') or contains(text(), 'api')]")
            for elem in api_elements[:5]:
                try:
                    href = elem.get_attribute('href')
                    src = elem.get_attribute('src')
                    text = elem.text.strip()
                    
                    if href and 'api' in href:
                        api_indicators.append({"type": "href", "value": href})
                    elif src and 'api' in src:
                        api_indicators.append({"type": "src", "value": src})
                    elif text and 'api' in text.lower():
                        api_indicators.append({"type": "text", "value": text})
                        
                except:
                    continue
            
            dynamic_info = {
                "frameworks": frameworks_detected,
                "element_counts": element_counts,
                "api_indicators": api_indicators
            }
            
            self.results["api_calls_detected"] = dynamic_info
            
            print(f"✅ 动态内容分析完成")
            print(f"  - JavaScript框架: {[k for k, v in frameworks_detected.items() if v]}")
            print(f"  - 总链接数: {element_counts['total_links']}")
            print(f"  - 总按钮数: {element_counts['total_buttons']}")
            print(f"  - API指示器: {len(api_indicators)}")
            
            return dynamic_info
            
        except Exception as e:
            print(f"❌ 动态内容检测失败: {e}")
            return {}
    
    def save_results(self):
        """保存分析结果"""
        try:
            output_file = "./release/url0_simple_analysis.json"
            
            # 确保release目录存在
            os.makedirs("./release", exist_ok=True)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(self.results, f, ensure_ascii=False, indent=2)
            
            print(f"💾 分析结果已保存到: {output_file}")
            return output_file
            
        except Exception as e:
            print(f"❌ 保存结果失败: {e}")
            return None
    
    def cleanup(self):
        """清理资源"""
        if self.base_driver:
            self.base_driver.cleanup()
            print("🧹 WebDriver已清理")
    
    def run_analysis(self):
        """运行分析"""
        try:
            print("🚀 开始URL0简化逆向分析...")
            print("=" * 50)
            
            # 1. 加载配置
            if not self.load_config():
                return False
            
            # 2. 初始化WebDriver
            if not self.setup_driver():
                return False
            
            # 3. 导航并分析页面
            if not self.navigate_and_analyze():
                return False
            
            # 4. 查找车款信息
            self.find_vehicle_models()
            
            # 5. 查找规格元素
            self.find_specification_elements()
            
            # 6. 检测动态内容
            self.detect_dynamic_content()
            
            # 7. 保存结果
            output_file = self.save_results()
            
            # 8. 打印摘要
            self.print_summary()
            
            return True
            
        except Exception as e:
            print(f"❌ 分析过程出现错误: {e}")
            return False
        finally:
            self.cleanup()
    
    def print_summary(self):
        """打印分析摘要"""
        print("\n" + "=" * 50)
        print("📊 URL0分析摘要")
        print("=" * 50)
        
        page_info = self.results.get("page_info", {})
        models = self.results.get("models_found", [])
        specs = self.results.get("specification_links", [])
        
        print(f"🎯 目标URL: {self.results['target_url']}")
        print(f"📄 页面标题: {page_info.get('title', 'N/A')}")
        print(f"📍 最终URL: {page_info.get('final_url', 'N/A')}")
        print(f"🚗 发现车款信息: {len(models)} 个")
        print(f"📋 发现规格元素: {len(specs)} 个")
        
        # 显示重要发现
        if models:
            print(f"\n🚗 主要车款信息:")
            for i, model in enumerate(models[:5]):
                print(f"  {i+1}. {model['text'][:50]}...")
        
        if specs:
            print(f"\n📋 主要规格元素:")
            for i, spec in enumerate(specs[:5]):
                print(f"  {i+1}. {spec['text'][:50]}...")
        
        print(f"\n💾 详细结果已保存到: ./release/url0_simple_analysis.json")

def main():
    """主函数"""
    analyzer = SimpleURL0Analyzer()
    success = analyzer.run_analysis()
    
    if success:
        print("\n🎉 URL0简化分析完成！")
    else:
        print("\n❌ URL0分析失败")
    
    return success

if __name__ == "__main__":
    main()
